package com.zp.self.module.工具.json转换.json_csv;
import org.apache.commons.io.FileUtils;
import org.json.CDL;
import org.json.JSONArray;
import org.json.JSONObject;
import org.json.JSONTokener;

import java.io.*;
import java.nio.charset.Charset;
import java.util.Set;

/**
 * @author ：by peng.zeng
 * @date ：Created 2021/9/3 15:05
 * @description ：整理
 */
public class Json2CsvOk多文件 {
    public static void main(String[] args) throws IOException {
        m4();
    }

    //分段组装String
    private static void m4() throws IOException {


        String outPathPart2 = "C:\\Users\\peng.zeng\\Desktop\\2021-11-01设备最后一次登录时间.csv";
        File file = new File(outPathPart2);

        JSONArray a5 = getJson("C:\\Users\\peng.zeng\\Desktop\\1.txt");
        JSONArray a6 = getJson("C:\\Users\\peng.zeng\\Desktop\\2.txt");


        //获取表头
        JSONArray names = null;
        JSONObject jo = a5.optJSONObject(0);
        if (jo != null) {
            names = jo.names();
            if (names != null) {
                String csv = CDL.rowToString(names);
                FileUtils.writeStringToFile(file, csv, Charset.defaultCharset(), true);
            } else {
                System.out.println("获取表头失败了--");
                return;
            }
        }

        writeData(file, CDL.toString(names, a5));
        writeData(file, CDL.toString(names, a6));

    }

    private static void writeData(File file, String s) throws IOException {
        String csv = s;
        FileUtils.writeStringToFile(file, csv, Charset.defaultCharset(), true);
    }

    private static void addElement(JSONArray jsonArraya, Set<String> idSet, Set<Object> list_100) {
        int size  =jsonArraya.length();
        for (int i = 0; i < size; i++) {
            JSONObject jsonObject = jsonArraya.getJSONObject(i);
            String id = jsonObject.getString("id");
            if(!idSet.contains(id)){
                list_100.add(jsonArraya.get(i));
                idSet.add(id);
            }
        }
    }

    private static JSONArray getJson(String inPath2) throws IOException {

        BufferedInputStream fis = new BufferedInputStream(new FileInputStream(inPath2));
        BufferedReader reader = new BufferedReader(new InputStreamReader(fis, "utf-8"), 5 * 1024 * 1024);// 用5M的缓冲读取文本文件
        JSONTokener jsonTokener = new JSONTokener(reader);
        JSONArray objects = new JSONArray(jsonTokener);
        fis.close();
        reader.close();
        return objects;
    }
}
